using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

namespace EventScavenger
{
    public partial class EventIDFilter : Form
    {
        private const string AllText = "All";

        #region Constructors
        public EventIDFilter()
        {
            InitializeComponent();
        } 
        #endregion

        #region Properties
        private List<int> selectedIds = new List<int>();
        public List<int> SelectedIds
        {
            get { return selectedIds; }
            set { selectedIds = value; }
        }
        private bool allEnabled;
        public bool AllEnabled
        {
            get { return allEnabled; }
            set { allEnabled = value; }
        }
        private bool allowNone = false;
        public bool AllowNone
        {
            get { return allowNone; }
            set { allowNone = value; }
        }

        #endregion

        #region Private stuff
        private EventScavengerDAL sqlEventSource; 
        private bool selfChecking = false;
        private List<int> availableEventIDs;
        private void ShowLoadingMessage()
        {
            lvwEventIDs.Items.Clear();
            lvwEventIDs.Items.Add("Loading...");
            System.Windows.Forms.Application.DoEvents();
        }
        private void LoadListView()
        {
            ListViewItem lvwi;
            if ((sqlEventSource.AvailableEventIDs != null) && (sqlEventSource.AvailableEventIDs.Count > 0))
            {
                availableEventIDs = sqlEventSource.AvailableEventIDs;
            }
            else
            {
                LoadEventIDs();
            }
            Cursor.Current = Cursors.WaitCursor;
            selfChecking = true;
            lvwEventIDs.Items.Clear();            
            try
            {
                lvwEventIDs.BeginUpdate();
                lvwi = new ListViewItem(AllText);

                if (allEnabled)
                {
                    lvwi.Checked = true;
                }
                lvwEventIDs.Items.Add(lvwi);
                foreach (int eventId in availableEventIDs)
                {
                    lvwi = new ListViewItem(eventId.ToString());
                    lvwi.Checked = (selectedIds.Contains(eventId)) || allEnabled;
                    lvwEventIDs.Items.Add(lvwi);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                lvwEventIDs.EndUpdate();
            }
            Cursor.Current = Cursors.Default;
            selfChecking = false;
        }
        private void LoadEventIDs()
        {
            try
            {
                availableEventIDs = sqlEventSource.GetEventIDList();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        public DialogResult Show(EventScavengerDAL sqlEventSource) 
        {
            this.sqlEventSource = sqlEventSource;

            return ShowDialog();
        }

        #region Form events
        private void EventIDFilter_Load(object sender, EventArgs e)
        {
            if ((Properties.Settings.Default.EventIDFilterLocation != null) && (!Properties.Settings.Default.EventIDFilterLocation.Equals(new Point(0, 0))))
            {
                this.Location = Properties.Settings.Default.EventIDFilterLocation;
            }
            if ((Properties.Settings.Default.EventIDFilterSize != null) && (!Properties.Settings.Default.EventIDFilterSize.Equals(new Size(0, 0))))
            {
                this.Size = Properties.Settings.Default.EventIDFilterSize;
            }

            //ensuring the previously selected item is visible again on startup
            new System.Threading.Thread(delegate()
                {
                    this.Invoke((MethodInvoker)delegate()
                        {
                            ShowLoadingMessage();
                            System.Threading.Thread.Sleep(500);
                            LoadListView();
                        }
                    );
                }
            ).Start();
        }
        private void EventIDFilter_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.WindowState == FormWindowState.Normal)
            {
                Properties.Settings.Default.EventIDFilterLocation = this.Location;
                Properties.Settings.Default.EventIDFilterSize = this.Size;
            }
            Properties.Settings.Default.Save();
        }
        private void lvwEventIDs_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            int selectedCount = 0;
            if (!selfChecking)
            {
                selfChecking = true;
                lvwEventIDs.BeginUpdate();
                if (e.Item.Text == AllText)
                {
                    foreach (ListViewItem lvwi in lvwEventIDs.Items)
                    {
                        if (lvwi.Text != AllText)
                        {
                            lvwi.Checked = e.Item.Checked;
                        }
                    }
                }
                else
                {
                    if (!e.Item.Checked)
                    {
                        lvwEventIDs.Items[0].Checked = false;
                    }
                    else
                    {
                        bool testAll = true;
                        foreach (ListViewItem lvwi in lvwEventIDs.Items)
                        {
                            if ((lvwi.Text != AllText) && (!lvwi.Checked))
                            {
                                testAll = false;
                            }
                        }
                        lvwEventIDs.Items[0].Checked = testAll;
                    }
                }
                lvwEventIDs.EndUpdate();
                selfChecking = false;
                foreach (ListViewItem lvwi in lvwEventIDs.Items)
                {
                    if (lvwi.Checked)
                        selectedCount++;
                }
                cmdOK.Enabled = (selectedCount > 0) || allowNone;
            }
        }
        private void cmdOK_Click(object sender, EventArgs e)
        {
            selectedIds = new List<int>();
            foreach (ListViewItem lvwi in lvwEventIDs.Items)
            {
                if (lvwi.Text != AllText)
                {
                    if (lvwi.Checked)
                        selectedIds.Add(int.Parse(lvwi.Text));
                }
                else
                    allEnabled = lvwi.Checked;
            }
            this.DialogResult = DialogResult.OK;
            Close();
        }
        private void cmdReload_Click(object sender, EventArgs e)
        {
            ShowLoadingMessage();
            LoadEventIDs();
            LoadListView();
        } 
        private void EventIDFilter_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
                Close();
        }
        #endregion

        #region Quick filter
        private void txtQuickSelect_TextChanged(object sender, EventArgs e)
        {
            if (txtQuickSelect.Text.Length > 0)
            {
                timerQuickSelect.Enabled = false; //cancel any previous event
                timerQuickSelect.Enabled = true;
            }
        }
        private void timerQuickSelect_Tick(object sender, EventArgs e)
        {
            timerQuickSelect.Enabled = false;
            if (txtQuickSelect.Text.Length > 0)
            {
                string quickFilter = txtQuickSelect.Text.ToLower();
                selfChecking = true;
                foreach (ListViewItem lvi in lvwEventIDs.Items)
                {
                    if (lvi.Text != AllText)
                    {
                        lvi.Checked = lvi.Text.ToLower().Contains(quickFilter);
                    }
                    else
                    {
                        lvi.Checked = false;
                    }
                }
                selfChecking = false;
                cmdOK.Enabled = (lvwEventIDs.CheckedItems.Count > 0) || allowNone;
            }
        }
        #endregion
        
    }
}